package com.converse.diamondreader.customized;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.TextPaint;

/**
 * Author: Administrator
 * Date: 2021/12/21
 * Project: DiamondReader
 * Description:
 */
public class RecognizeTextView {
    private TrackBoxLayerView mParentView;
    private String mText;
    private Rect mTextFrame;
    private static final int DEFAULT_TEXT_SIZE_DP = 5;
    private float mTextSizePx=DEFAULT_TEXT_SIZE_DP;
    private TextPaint mTextPainter;
    private Paint mFramePainter;

    public RecognizeTextView(String text, Rect textFrame) {
        mText = text;
        mTextFrame = textFrame;

        mTextPainter = new TextPaint();
        mTextPainter.setStyle(Paint.Style.FILL);
        mTextPainter.setTextSize(mTextSizePx);
        mTextPainter.setColor(Color.WHITE);
        mTextPainter.setAntiAlias(true);

        mFramePainter = new Paint();
        mFramePainter.setColor(Color.GREEN);
        mFramePainter.setStyle(Paint.Style.STROKE);
        mFramePainter.setStrokeMiter(2);
    }

    public void attach(TrackBoxLayerView parentView){
        mParentView.addRecognizeView(this);
    }

    public void draw(Canvas canvas){
        adjustTextSizeToFitFrame(mText, mTextFrame);
        canvas.drawText(mText, mTextFrame.left, mTextFrame.bottom, mTextPainter);
        canvas.drawRect(mTextFrame, mFramePainter);
    }

    private void adjustTextSizeToFitFrame(String text, Rect displayBound) {
        Rect tempBound = new Rect();
        mTextPainter.getTextBounds(text, 0, text.length(), tempBound);
        while (tempBound.width() <= displayBound.width() && tempBound.height() <= displayBound.height()) {
            mTextSizePx += 1;
            mTextPainter.setTextSize(mTextSizePx);
            mTextPainter.getTextBounds(text, 0, text.length(), tempBound);
        }
    }


}
